<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/11/25
 * Time: 19:17
 */
namespace app\common\model;

use app\common\helper\setting_helper;
use think\Model;

class Appmenu extends Model
{
    protected $createTime = 'add_time';

    /**
     * 检查app的token是否可用
     */
    public static function check_menu_token()
    {
        $appmenu_key = setting_helper::get_setting_info('appmenu_key');
        if ($appmenu_key) {
            $appmenu_key = unserialize($appmenu_key);
        }
        if (!$appmenu_key || !isset($appmenu_key['access_token'])) {
            return false;
        }
        /* $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appmenu_key['appid']."&secret=".$appmenu_key['appsecret'];
        $access_token = self::get_access_token($token_url);
        if (!$access_token) {
            return false;
        } */

        return true;
    }

    /**
     * 取得菜单列表
     * @param int $parent_id
     * @return array
     */
    public static function get_menu_list($parent_id = 0, $store_id = 0)
    {
        $filter = array('store_id'=>$store_id, 'parent_id'=>$parent_id);

        $list = Appmenu::where($filter)->order('view_order')->select()->toArray();
        if (!$parent_id) {
            foreach ($list as $k=>$v) {
                $list[$k]['son_list'] = self::get_menu_list($v['id'], $store_id);
            }
        }

        return $list;
    }


    /**
     * 取得菜单数量
     */
    public static function get_menu_num($parent_id = 0, $store_id = 0)
    {
        $filter = array('store_id'=>$store_id, 'parent_id'=>$parent_id, 'status'=>1);

        return _model('appmenu', $filter, 'count');
    }

    /**
     * 取自定义菜单
     * @param int $parent_id
     * @param int $open_card_id
     * @param int $company_id
     * @return array
     */
    public static function get_menu_list_for_weixin($parent_id = 0, $store_id = 0)
    {
        $filter = array('store_id'=>$store_id, 'parent_id'=>$parent_id, 'status'=>1);

        $list = getList('appmenu',$filter, ['view_order', 'asc'],0);
        foreach ($list as $k=>$v) {
            $filter['parent_id'] = $v['id'];
            $list[$k]['son_list'] = getList('appmenu',$filter, ['view_order', 'desc'], 0);
        }

        return $list;
    }


    /**
     * 通过接口取得新的access_token
     * @param unknown_type $token_url
     * @return boolean
     */
    public static function get_access_token($token_url)
    {
        $response = curl($token_url);
        if (isset($response->access_token)) {
            return $response->access_token;
        }

        return false;
    }
}